<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href='/plug-in/pear/css/pear.css' media="all">
    <link rel="stylesheet" href='/css/base.css'>
    <style>
        .layui-upload-list .layui-table th {
            text-align: center;
            font-weight: 800;
        }

        .layui-upload-list .layui-table th+th {
            width: 70px;
        }
        .role-box xm-select{
            border: 0;
        }
        .role-box .xm-label.auto-row{
            display: none;
        }
    </style>
</head>
<body>
<div id="search-box">
    <form class="layui-form" action="" lay-filter="search-form">
        <div class="layui-input-inline">
            <input style="height: 31px;" class="layui-input" name="title" placeholder="请输入用户昵称进行搜索"
                   autocomplete="off">
        </div>
        <button class="layui-btn layui-btn-sm layui-bg-green" lay-submit
                lay-filter="reload"><span class="fa fa-search" aria-hidden="true"></span> 搜索
        </button>
    </form>
</div>
<div class="page-content" shiro:hasPermission="system.user.list">
    <table class="layui-hide" id="table" lay-filter="table"></table>
</div>

<div class="form-box" style="width: auto;padding: 30px;box-sizing: border-box;display: none">
    <form class="layui-form" action="" lay-filter="form-obj" style="margin: 10px;">
        <div class="layui-form-item">
            <label style="width: 60px" class="layui-form-label towexin-form-label layui-required">用户名：</label>
            <div class="layui-input-block" style="margin-left: 80px">
                <input type="text" name="username" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <label style="width: 70px" class="layui-form-label towexin-form-label layui-required">用户昵称：</label>
            <div class="layui-input-block" style="margin-left: 90px">
                <input type="text" name="nickname" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <div class="layui-input-block">
                <input type="text" name="id" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label style="width: 60px" class="layui-form-label towexin-form-label layui-required">密码：</label>
            <div class="layui-input-block" style="margin-left: 80px">
                <input type="password" name="password" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
                <button type="submit" id="submit-type" class="pear-btn pear-btn-primary" lay-submit=""
                        lay-filter="add">立即提交
                </button>
            </div>
        </div>
    </form>
</div>

<div class="role-box" style="display: none;padding: 20px">
    <div id="setTree" style="margin-right: 2px;" class="xm-select-demo"></div>
</div>

<script type="text/html" id="toolbarTop">
    <div class="layui-btn-container">
        <button shiro:hasPermission="system.user.list" class="layui-btn layui-btn-sm layui-bg-black" lay-event="refresh"><span class="fa fa-refresh"
                                                                                        title="刷新表格" aria-hidden="true"></span></button>
        <button shiro:hasPermission="system.user.add" class="layui-btn layui-btn-sm layui-bg-blue" lay-event="add"><span class="fa fa-plus-circle"
                                                                                   aria-hidden="true"></span> 新增</button>
        <button shiro:hasPermission="system.user.delete" class="layui-btn layui-btn-sm layui-bg-red layui-hide" id="isDel" lay-event="del"><span
                class="fa fa-trash-o" aria-hidden="true"></span> 删除</button>
    </div>
</script>
<script type="text/html" id="barRight">
        {{#  if(userIds.indexOf(d.id)==-1){ }}
        <a shiro:hasPermission="system.user.edit" class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a shiro:hasPermission="system.user.delete" class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
        <a shiro:hasPermission="system.user.assignation" class="layui-btn layui-btn-xs layui-btn-normal" lay-event="assign">分配角色</a>
        {{#  }else{ }}
            {{#  if(userName==d.username){ }}
            <a shiro:hasPermission="system.user.edit" class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            {{#  }else{ }}
            <span class="layui-badge">无权操作</span>
            {{#  } }}
        {{#  } }}
</script>

<script type="text/html" id="status">
    <input shiro:hasPermission="system.user.status" {{userIds.indexOf(d.id)!==-1?"disabled":""}} type="checkbox" lay-skin="switch" {{d.status===false?"checked":""}} lay-filter="status" lay-text="TRUE|FALSE" value="{{d.username}}">
    <input shiro:lacksPermission="system.user.status" disabled type="checkbox" lay-skin="switch" {{d.status===false?"checked":""}} lay-text="TRUE|FALSE">
</script>

<script src="/plug-in/jquery/jquery-3.5.1.min.js" charset="utf-8"></script>
<script src='/plug-in/layui/layui.js' charset="utf-8"></script>
<script src='/plug-in/lay-config.js' charset="utf-8"></script>
<script shiro:hasPermission="system.user.list" th:inline="javascript" type="text/javascript">

    let form = layui.form, layer = layui.layer, table = layui.table;

    window.userIds = [[${userIds}]];
    window.userName = [[${userName}]];

    let tab = table.render({
        elem: '#table',
        url: '/user/selectPage',
        page: {
            layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
            groups: 3, //只显示 1 个连续页码
        },
        //height: "full-110",
        limit: 15,
        skin: "line",
        limits: [15, 30, 45],
        toolbar: '#toolbarTop', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: null,
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "total": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        },
        response: {
            statusCode: 200, //规定成功的状态码，默认：0
            countName: 'total' //规定数据总数的字段名称，默认：count
        },
        cols: [
                [
                {type: 'checkbox', fixed: 'left'},
                {field: "username", minWidth: 120, title: '用户名'},
                {field: "nickname", minWidth: 120, title: '用户昵称'},
                {width: 110, title: '角色', templet: function (d) {
                    return d.role_name?'<span class="layui-badge layui-bg-cyan">'+d.role_name+'</span>':'<span class="layui-badge layui-bg-gray">未分配</span>'
                }},
                {title: '冻结', width: 110, templet: '#status'},
                {title: '状态', width: 100, templet: (d)=>{
                    return  d.online?'<span class="layui-badge layui-bg-green" style="background-color: #4caf50 !important">在线</span>':'<span class="layui-badge layui-bg-gray" style="background-color: #eaeaea!important">离线</span>'
                    }},
                {field: "created_time", width: 180, sort: true, title: '创建时间'},
                {field: "update_time", width: 180, sort: true, title: '修改时间'},
                {title: '操作', toolbar: '#barRight', width: 240, unresize: true, fixed: 'right'}
            ]
        ],
        done: ()=>{
            let maxHeight = $(".layui-table-body.layui-table-main").css("height");
            $(".layui-table-body.layui-table-main").removeAttr("style").css("max-height", maxHeight)
        }
    });

    //监听状态操作
    form.on('switch(status)', function(obj){
        layer.load()
        $.ajax({
            url: "/user/changeStatus",
            data: {userName: obj.value, status: !obj.elem.checked},
            success: function (res) {
                if (res.code === 200) {
                    layer.closeAll()
                    layer.tips("操作成功", obj.othis);
                } else if(res.code === 401){
                    layer.closeAll()
                    layer.tips(res.msg, obj.othis);
                }else {
                    layer.closeAll('loading')
                    layer.tips("操作失败", obj.othis);
                }
                tab.reload()
            },
            error(){
                layer.closeAll('loading')
                layer.msg("服务出错")
            }
        })
    });


    table.on('toolbar(table)', function(obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'refresh':
                form.val("search-form", {
                    title: ""
                })
                tab.reload({
                    page: {
                        curr: 1
                    },
                    where: {
                        nickname: ""
                    }
                })
                break;
            case 'add':
                form.val("form-obj", {username: "", password: "", id: ""})
                $("input[name=password]").parent().parent().show()
                $("input[name=password]").attr("lay-verify", "required")
                $("input[name=username]").parent().parent().show()
                $("input[name=username]").attr("lay-verify", "required")
                $("input[name=nickname]").parent().parent().addClass("layui-hide")
                $("input[name=nickname]").removeAttr("lay-verify")
                layer.open({
                    type: 1,
                    content: $(".form-box"),
                    title: false,
                    //area: ["300px", "200px"],
                    scrollbar: false
                })
                break;
        };
    });



    //监听行工具事件
    table.on('tool(table)', function(obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            form.val("form-obj", {username: "", password: "", id: ""})
            $("input[name=password]").parent().parent().hide()
            $("input[name=password]").removeAttr("lay-verify")
            $("input[name=username]").parent().parent().hide()
            $("input[name=username]").removeAttr("lay-verify")
            $("input[name=nickname]").parent().parent().removeClass("layui-hide")
            $("input[name=nickname]").attr("lay-verify", "required")
            form.val("form-obj", data)
            layer.open({
                type: 1,
                content: $(".form-box"),
                title: false,
                //area: ["300px", "200px"],
                scrollbar: false
            })
        } else if(obj.event === "del"){
            layer.confirm('确定删除 <span style="color: red; font-weight: 800">' + data.username + '</span> 么？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                layer.load()
                $.ajax({
                    url: '/user/delete',
                    data: {id: data.id},
                    success: function (result) {
                        if (result.code == 200) {
                            tab.reload();
                            layer.closeAll('loading')
                            layer.msg("删除成功")
                        } else {
                            layer.closeAll('loading')
                            layer.msg("删除失败")
                        }
                        ;
                    },
                    error: function () {
                        layer.closeAll('loading')
                        layer.msg("请求失败")
                    }
                });
            });
        } else if(obj.event === "assign"){
            window.uId = data.id
            setTree.setValue([data.r_id||""])
            layer.open({
                type: 1,
                content: $(".role-box"),
                title: false,
                //area: ["300px", "200px"],
                scrollbar: false
            })
        }
    });

    table.on('checkbox(table)', function(obj){
        var checkStatus = table.checkStatus("table");
        if(checkStatus.data.length>0){
            $("#isDel").removeClass("layui-hide")
            // $(".move-btn").removeClass("layui-hide")
        }else{
            $("#isDel").addClass("layui-hide")
            // $(".move-btn").addClass("layui-hide")
        }
    });

    form.on('submit(reload)', function (data) {
        console.log(data)
        tab.reload({
            where: {
                nickname: data.field.title
            }
        })
        return false;
    })

    layui.use(["hash"], function () {
        form.on('submit(add)', function (data) {
            layer.load()
            data.field.password = data.field.password!==""&&data.field.password!=null?layui.hash.md5(data.field.password):null;
            $.ajax({
                url: data.field.id!==null&&data.field.id!==""?"/user/update":"/user/save",
                type: "POST",
                data: data.field,
                success: function (res) {
                    if (res.code === 200) {
                        tab.reload();
                        layer.closeAll()
                        layer.msg("操作成功")
                    }else if(res.code === 201){
                        layer.closeAll()
                        layer.msg("操作成功")
                        window.location.reload()
                    }else {
                        layer.closeAll('loading')
                        layer.msg(res.msg)
                    }
                },
                error: function () {
                    layer.closeAll('loading')
                    layer.msg("请求失败")
                }
            })

            return false;
        });
    })

    layui.use(["xmSelect"], function(){
        let xmSelect = layui.xmSelect;

        window.setTree = xmSelect.render({
            el: '#setTree',
            autoRow: true,
            filterable: true,
            paging: true,
            radio: true,
            searchTips: '搜索角色',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 35,
                expandedKeys: true,
                strict: false,
                //点击节点是否展开
                clickExpand: true,
                clickCheck: false,
            },
            model: {
                type: 'relative',
            },
            on: function(data) {
                if(data.arr.length > 0){
                    layer.load()
                    $.ajax({
                        type: "POST",
                        url: "/user/setRole",
                        data: {uId: uId, rId: data.arr[0].value},
                        success:function(res){
                            layer.closeAll()
                            if(res.code==200){
                                tab.reload()
                                layer.msg("分配成功");
                            }else{
                                layer.msg("分配失败");
                            }
                        },
                        error() {
                            layer.closeAll()
                            layer.msg("请求失败");
                        }
                    })
                }
            },
            theme: {
                color: '#00aa7f',
            },
            height: '360px',
        })

        $.ajax({
            url: "/role/selectUserRoleTree",
            success: function (res) {
                setTree.update({
                    data: res.data
                })
                setTree.changeExpandedKeys(true)
            },
            error(){
                layer.closeAll()
            }
        })
    })

</script>
</body>
</html>